package com.security.demo.dao;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.security.demo.model.User;
import com.security.demo.util.Pager;

@Repository
public class UserDao extends SimpleJdbcDao<User> {

	public static String usernameSql = "select * from t_user where username = ?";
	public static String findCountById = "select count(*) from t_user where id = ?";
	public static String insertSql = "insert into t_user (id,username,password,nickname,salt,createtime,sex,phone,locked) values (:id,:username,:password,:nickname,:salt,:createtime,:sex,:phone,:locked)";
	public static String insertUserRoleSql = "insert into t_user_role (user_id,role_id) values (?,?)";
	public static String updateSql = "update t_user set username = :username ,password = :password ,nickname = :nickname ,salt = :salt ,createtime = :createtime ,sex = :sex ,phone = :phone ,locked = :locked  where id = :id ";
	public static String findPermissionSql = "select s.permission from t_resource s left join t_role_resource rs on s.id = rs.resource_id "
			+ " left join t_role r on rs.role_id = r.id " + " left join t_user_role ur on ur.role_id = r.id "
			+ " left join t_user u on ur.user_id = u.id " + " where u.username = ?";
	public static String findRoleIdsSql = "select ur.role_id from t_user_role ur where ur.user_id = ?";
	public static String deleteUserRoleSql = "delete from t_user_role where user_id = ?";

	public User findByUsername(String username) {
		return findModel(usernameSql, username);
	}

	public Pager<User> findPager(int start, int limit, Object... args) {
		String sql = "select * from t_user ";
		if (ArrayUtils.isNotEmpty(args))
			sql += " where username like ? or nickname like ?";
		else
			args = NULL_PARA_ARRAY;
		return super.findPager(start, limit, sql, args);
	}

	public Set<String> findPermissions(String username) {
		List<String> permissions = findStrings(findPermissionSql, username);
		if (permissions != null) {
			return new HashSet<String>(permissions);
		}
		return Collections.emptySet();
	}

	public Set<String> findRoleIds(String userId) {
		List<String> roleIds = super.findStrings(findRoleIdsSql, userId);
		return roleIds != null && roleIds.size() > 0 ? new HashSet<String>(roleIds) : this.emptySet;
	}

	public boolean saveUser(User user) {
		String userId = getId();
		user.setId(userId);
		saveModel(insertSql, user);// save user
		List<String> roleIds = user.getRoleIds();
		if (CollectionUtils.isNotEmpty(roleIds)) { // save user-role
			for (String roleId : roleIds) {
				jdbcTemplate.update(insertUserRoleSql, new Object[] { userId, roleId });
			}
		}
		return true;
	}

	public boolean updateUser(User user) {
		saveModel(updateSql, user); // update user
		List<String> roleIds = user.getRoleIds();
		jdbcTemplate.update(deleteUserRoleSql, new Object[] { user.getId() });
		if (CollectionUtils.isNotEmpty(roleIds)) { // save user-role
			for (String roleId : roleIds) {
				jdbcTemplate.update(insertUserRoleSql, new Object[] { user.getId(), roleId });
			}
		}
		return true;
	}

	public boolean mergeUser(User user) {
		return StringUtils.isBlank(user.getId()) ? saveUser(user) : updateUser(user);
	}
}
